package com.bix.util.blizfiles;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.log4j.Logger;

import com.jme.util.resource.ResourceLocator;

/**
 * This class represents a resource locator for finding files used by Blizzard
 * Entertainment.  The ultimate goal of this class would be to actually wrap
 * up a MPQ file and provide the necessary framework for returning URLs to the
 * data inside of the MPQ so that it didn't have to be entire extracted to
 * work.  Btw, that's a long term goal :P.
 * 
 *	@author		squid
 * 
 *	@version	1.0.0
 */
public class BlizzardResourceLocator implements ResourceLocator {
	private static final Logger log = Logger.getLogger (BlizzardResourceLocator.class.getName ());

	private List<String> directories = new ArrayList<String> ();

	/**
	 * Instantiate the locator using a directory prefix of where to find the
	 * resources.
	 * 
	 * @param rootDirectoryPrefix
	 *          The root directory to search.
	 */
	public BlizzardResourceLocator(String rootDirectoryPrefix) {
		StringTokenizer st = new StringTokenizer (rootDirectoryPrefix, ";");
		while (st.hasMoreTokens ()) {
			String directory = st.nextToken ();
			if (directory.endsWith ("/") == false) {
				directory = directory + "/";
			}
			System.out.println ("Adding: " + directory);
			this.directories.add (directory);
		}
	}

	/**
	 * Locates a resource using the name and the set of directories that this
	 * locator has references to.
	 * 
	 * @param resourceName
	 *          The name of the resource to find.
	 * 
	 * @return A URL to the resource.
	 */
	public URL locateResource (String resourceName) {
		try {
			for (String prefix : this.directories) {
				String	path = prefix + resourceName;
				path = path.replaceAll(" ", "%20");

				//
				// Replace spaces with %20s.
				//
				URL url = new URL (path);
				File f = new File (url.toURI ());
				if (f.exists ()) {
					log.debug ("Resource Found: " + url.toURI ());
					return url;
				}
			}
			
			//
			// Special case to try and load the resource using just the name.
			//
			try {
				URL url = new URL (resourceName);
				File f = new File (url.toURI ());
				if (f.exists ()) {
					log.debug ("Resource found: " + url.toURI ());
					return url;
				}
			} catch (MalformedURLException e) {
			}
			
			log.warn ("Resource: " + resourceName + " not found.");
			return null;
		} catch (MalformedURLException e) {
			e.printStackTrace ();
			return null;
		} catch (URISyntaxException e) {
			e.printStackTrace ();
			return null;
		}
	}
}
